<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\UserCreate;
use App\Http\Requests\Admin\UserUpdate;
use App\Models\Admin\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('admin.users.index', compact('users'));
    }

    public function create()
    {
        return view('admin.users.create');
    }

    public function store(UserCreate $request)
    {
        $data = $request->all();
        $data['password'] = bcrypt($data['password']);
        if (User::create($data)) {
            return redirect()->to(route('admin.users'))->with(['status' => '添加用户成功']);
        }
        return redirect()->to(route('admin.users'))->withErrors('系统错误');
    }

    public function edit($id)
    {
        $user = User::findOrFail($id);
        return view('admin.users.edit', compact('user'));
    }

    public function update(UserUpdate $request, $id)
    {
        $user = User::findOrFail($id);
        $data = $request->except('password');
        if ($request->get('password')){
            $data['password'] = bcrypt($request->get('password'));
        }
        if ($user->update($data)){
            return redirect()->to(route('admin.users'))->with(['status'=>'更新用户成功']);
        }
        return redirect()->to(route('admin.users'))->withErrors('系统错误');
    }
}
